package com.shilupan.panbao.riskmodel.httpclient;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Response 响应结果 Json解析 Handler
 *
 * @author pacey
 */
@Slf4j
public class JsonResponseHandler {
	public static <T> ResponseHandler<T> createResponseHandler(final Class<T> clazz){
		return new JsonResponseHandlerImpl<T>(null,clazz);
	}

	public static class JsonResponseHandlerImpl<T> extends LocalResponseHandler implements ResponseHandler<T> {
		
		private Class<T> clazz;
		
		public JsonResponseHandlerImpl(String uriId, Class<T> clazz) {
			this.uriId = uriId;
			this.clazz = clazz;
		}


		@Override
		public T handleResponse(HttpResponse response)
				throws ClientProtocolException, IOException {
			int status = response.getStatusLine().getStatusCode();
			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				String str = StringUtils.defaultIfBlank
						(EntityUtils.toString(entity,"utf-8"),"");
				log.info("URI[{}] elapsed time:{} ms RESPONSE DATA STATUS:{} content:[{}]",super.uriId,System.currentTimeMillis()-super.startTime,status,
						str.length()<2048?str:str.length());
				if (StringUtils.isNotEmpty(str)) {
					try {
						return JSON.parseObject(str, clazz);
					} catch (Exception e) {
						log.error("URI[{}] 数据源返回JSON格式错误{}",super.uriId, str);
						return null;
					}
				} else {
					return null;
				}
			} else if ((status >= 400 && status < 405) || status == 413){
				log.info("Unexpected response status: " + status);
				HttpEntity entity = response.getEntity();
				String str = EntityUtils.toString(entity,"utf-8");
				if (StringUtils.isNotEmpty(str)) {
					return JSON.parseObject(str, clazz);
				} else {
					log.error("Unexpected response status: " + status);
					return null;
				}
			} else {
				return null;
			}
		}

		
	}
}
